import pyautogui as pg
import os
import time
import pyperclip
import requests
import json
import psutil
import sys
import win32gui, win32com.client, win32api
import win32con
import win32process  
import ctypes
from pywinauto.application import Application
import re


def open_software_golden(dir_path) :
    file_list = os.listdir(dir_path)
    list = []
    for file_name in file_list :
        if (file_name.startswith("广联达") or "GCCP" in file_name):
            list.append(file_name)
    os.startfile(dir_path + "\\" + list[0])

def set_foreground_window(hwnd):  
    _, pid = win32process.GetWindowThreadProcessId(hwnd)
    ctypes.windll.user32.AllowSetForegroundWindow(pid)
    shell = win32com.client.Dispatch("WScript.Shell")
    shell.SendKeys('%{1}')
    win32gui.SetForegroundWindow(hwnd)

def find_latest_swt_file_golden(directory):  
    latest_swt_file = None  
    latest_mtime = 0  
  
    # 遍历目录  
    for root, dirs, files in os.walk(directory):  
        for file in files:  
            # 检查文件是否以.swt结尾  
            print(file)
            if file.endswith('.SWT') or file.endswith('.swt'):  
                # 获取文件的完整路径  
                file_path = os.path.join(root, file)  
                # 获取文件的最后修改时间  
                mtime = os.path.getmtime(file_path)  
                # 如果这是最新的.swt文件，则更新latest_swt_file和latest_mtime  
                if mtime > latest_mtime:  
                    latest_swt_file = file_path  
                    latest_mtime = mtime  
  
    return latest_swt_file  

hwnd_title = dict()

def get_all_hwnd(hwnd,mouse):
    if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
        hwnd_title.update({hwnd:win32gui.GetWindowText(hwnd)})


def init_export_golden():
    windows_hwnd = 0

    while True:
        if not windows_hwnd:
            win32gui.EnumWindows(get_all_hwnd, 0)   
            for h,t in hwnd_title.items():
                if "- 投标管理 - 广联达预算计价" in t:
                # print(h, t)
                    windows_hwnd = h
            time.sleep(1)
            pg.hotkey("enter")
        else :
            break
        # 获取屏幕分辨率  
    screen_width = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)
    screen_height = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)

    # 获取窗口当前位置和大小  
    left, top, right, bottom = win32gui.GetWindowRect(windows_hwnd)
    window_width = right - left  
    window_height = bottom - top  

    # 计算新位置  
    new_left = (screen_width - window_width) // 2  
    new_top = (screen_height - window_height) // 2  

    # 移动窗口  
    win32gui.SetWindowPos(windows_hwnd, win32con.HWND_TOP, new_left, new_top, 1280, 760, 0)

    left, top, right, bottom = win32gui.GetWindowRect(windows_hwnd)

    print(str(left) + " " + str(top) + " " + str(right) + " " + str(bottom))
    pg.click((right - left) * (1 * (1.75 / 13)) + left, (bottom - top) * ((1.0 / 20) * 1) + top)
    time.sleep(0.5)
    pg.click((right - left) * (1 * (1.75 / 18)) + left, (bottom - top) * ((1.0 / 10) * 1) + top)
    time.sleep(0.5)
    pg.hotkey("esc")
    time.sleep(0.5)
    pg.hotkey("left")
    pg.hotkey("space")
    pg.typewrite("c:\\gloden_files")
    time.sleep(0.5)
    pg.hotkey("enter")
    pg.hotkey("enter")
    pg.hotkey("tab")
    pg.typewrite("1")
    time.sleep(1)
    pg.hotkey("enter")

def close_software_golden():
    pids = psutil.pids()
    for pid in pids:
        p = psutil.Process(pid)
        process_name = p.name()
        if 'GCCP' in process_name:
            # 杀掉指定进程
            # print('kill process: name: %s - pid: %s' %(process_name, pid))
            find_kill = 'taskkill -f -pid %s' % pid
            os.popen(find_kill)

def export_file_golden():
    time.sleep(1)
    hwnd = win32gui.FindWindow(None, "投标信息")
    left, top, right, bottom = win32gui.GetWindowRect(hwnd)
    screen_width = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)  
    screen_height = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)  
    window_width = right - left  
    window_height = bottom - top  

    # 计算新位置  
    new_left = (screen_width - window_width) // 2  
    new_top = (screen_height - window_height) // 2  

    set_foreground_window(hwnd)
    pg.hotkey("tab")
    pg.typewrite("1")
    # 移动窗口  
    # win32gui.SetWindowPos(hwnd, win32con.HWND_TOP, new_left, new_top, 551, 451, 0)
    tips =  win32gui.FindWindow(None, "提示")
    if tips:
        pg.click((right - left) * (1 * (10 / 13)) + left, (bottom - top) * ((18.5 / 20) * 1) + top)

        time.sleep(1)
        pg.hotkey("enter")
        pg.typewrite("1")
    # 移动窗口  
    # win32gui.SetWindowPos(hwnd, win32con.HWND_TOP, new_left, new_top, 551, 451, 0)
    tips2 =  win32gui.FindWindow(None, "提示")
    if tips2:
        pg.click((right - left) * (1 * (10 / 13)) + left, (bottom - top) * ((18.5 / 20) * 1) + top)

        time.sleep(1)
        pg.hotkey("enter")
        pg.hotkey("tab")
        pg.typewrite("1")
        pg.hotkey("enter")
        pg.hotkey("down")
        pg.hotkey("enter")
    pg.hotkey("enter")
    # 移动窗口  
    # win32gui.SetWindowPos(hwnd, win32con.HWND_TOP, new_left, new_top, 551, 451, 0)
    pg.click((right - left) * (1 * (10 / 13)) + left, (bottom - top) * ((18.5 / 20) * 1) + top)
    pg.hotkey("enter")
    time.sleep(0.5)
    pg.hotkey("enter")
    time.sleep(0.5)
    pg.hotkey("enter")

    while True:
        time.sleep(5)
        # 导出成功
        success_hwnd = win32gui.FindWindow(None, "成功")
        if success_hwnd:
            app = Application(backend='uia').connect(handle=success_hwnd)
            dlg = app.window(title=win32gui.GetWindowText(success_hwnd))  

            # 遍历子控件，找到包含文本信息的Static控件  
            # 注意：这里假设我们知道Static控件的精确路径或可以通过某种方式唯一地识别它  
            # 在实际情况中，你可能需要遍历所有子控件并检查它们的属性来找到它  
            static_control = dlg.child_window(control_type="Text", found_index=1)  # found_index可能需要根据实际情况调整  

            text = static_control.window_text()
            print(text)
            match = re.search(r".:/.*?_投标书/" , text)
            if match:  
                directory = match.group(0)  
                print(directory)  
            else:  
                print("未找到匹配的目录地址")
            directory = directory + '电子投标书/'
            final_file = find_latest_swt_file_golden(directory)
            print(final_file)
            return final_file
        
def pick_first_file_golden(windows_hwnd):
    screen_width = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)
    screen_height = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)

    # 获取窗口当前位置和大小  
    left, top, right, bottom = win32gui.GetWindowRect(windows_hwnd)
    window_width = right - left  
    window_height = bottom - top  

    # 计算新位置  
    new_left = (screen_width - window_width) // 2  
    new_top = (screen_height - window_height) // 2  

    # 移动窗口  
    win32gui.SetWindowPos(windows_hwnd, win32con.HWND_TOP, new_left, new_top, 1280, 760, 0)

    left, top, right, bottom = win32gui.GetWindowRect(windows_hwnd)
    pg.doubleClick((right - left) * (0.5) + left, (bottom - top) * ((1.5 / 10) * 1) + top)

def open_file_golden():
    # print(file_name)
    # win32gui.EnumWindows(get_all_hwnd, 0)   
    # for h,t in hwnd_title.items():
    #     print(t)
    print("123")
    hwnd =  win32gui.FindWindow(None, "广联达云计价平台GCCP6.0")
    while True:
        if not hwnd:
            time.sleep(1)
            hwnd =  win32gui.FindWindow(None, "广联达云计价平台GCCP6.0")
        else:
            break
    print(hwnd)
    print("321")
    set_foreground_window(hwnd)
    screen_width = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)
    screen_height = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)

    # 获取窗口当前位置和大小  
    left, top, right, bottom = win32gui.GetWindowRect(hwnd)
    window_width = right - left  
    window_height = bottom - top  

    # 计算新位置  
    new_left = (screen_width - window_width) // 2  
    new_top = (screen_height - window_height) // 2  

    # 移动窗口  
    win32gui.SetWindowPos(hwnd, win32con.HWND_TOP, new_left, new_top, 1280, 760, 0)
    app = Application(backend='uia').connect(handle=hwnd)
    dlg = app.window(title=win32gui.GetWindowText(hwnd))  
    button = dlg.child_window(title="本地文件", control_type="Button", found_index = 0)
    button.click_input()
    # print(dlg.print_ctrl_ids())
    button1 = dlg.child_window(title="本地文件", control_type="Button", found_index = 1)
    button1.click_input()
    button1 = dlg.child_window(title="本地文件", control_type="Button", found_index = 0)
    button1.click_input()
    edit = dlg.child_window(control_type="Edit", found_index = 0)
    edit.click_input()
    pg.hotkey("ctrl", "a")
    pg.typewrite("C")
    pg.hotkey("enter")
    pg.hotkey("enter")
    time.sleep(1)
    # print(dlg.print_control_identifiers())
    pick_first_file_golden(hwnd)
    edit.click_input()
    pg.hotkey("ctrl", "a")
    pg.typewrite("gloden_files")
    pg.hotkey("enter")
    pg.hotkey("enter")
    time.sleep(1)
    pick_first_file_golden(hwnd)
    edit.click_input()
    pg.hotkey("ctrl", "a")
    pg.hotkey("backspace")
    pg.hotkey("enter")
    pg.hotkey("enter")
    time.sleep(1)
    pick_first_file_golden(hwnd)
    time.sleep(5)
    pg.hotkey("enter")
    time.sleep(1)
    
def export_success(id, file_name, file_path):
    url = '''http://127.0.0.1:9135/rpa/runSuccess'''
    data = {
        "id" : id,
        "fileName" : file_name,
        "filePath" : file_path
    }
    headers = {
        'Content-Type': 'application/json'
    }
    requests.post(url = url, data = json.dumps(data), headers= headers)


# 异常处理
def export_failed(id, errorMsg):
    url = '''http://127.0.0.1:9135/rpa/runFailed'''
    data = {
        "id" : id,
        "errMsg": errorMsg
    }
    headers = {
        'Content-Type': 'application/json'
    }
    requests.post(url = url, data = json.dumps(data), headers=headers)

pg.FAILSAFE = False 

# 程序被唤起 参数为文件本地地址 文件id
dir_path = sys.argv[1]
need_export_file_name = sys.argv[2]
id = int(sys.argv[3])

try :
    close_software_golden()
    open_software_golden('C:\\')
    # time.sleep(3)
    open_file_golden()
    init_export_golden()
    file = export_file_golden()
    directory_path, file_name = os.path.split(file)  
    export_success(id, file_path= directory_path, file_name = file_name)
except Exception as e:
    close_software_golden()
    export_failed(id, str(e))
    # print(str(e))
    time.sleep(5)